"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Trash2, Plus } from "lucide-react"
import CommonSelector from "@/components/CommonSelector"
import ComboboxMultiGroupSelector from "@/components/ComboboxMultiGroupSelector"
import { format, differenceInHours } from "date-fns"
import {
  getCourseAppointmentClients,
  getCourseAppointmentPackages,
  getCourseAppointmentAssistantCoaches
} from "@/lib/appointmentService"

export default function EditAppointmentForm({
  appointment,
  campuses,
  coaches,
  courts,
  onSuccess,
  addAssistantCoach,
  removeAssistantCoach,
  addClientWithPackage,
  removeClientWithPackage,
  getCoursePackages,
  getAllUsers
}) {
  const [clients, setClients] = useState([])
  const [packages, setPackages] = useState([])
  const [assistantCoaches, setAssistantCoaches] = useState([])
  const [clientAndCoursePackages, setClientAndCoursePackages] = useState([])

  // 新增状态
  const [selectedCoachId, setSelectedCoachId] = useState("")
  const [coachRate, setCoachRate] = useState(3)
  const [selectedClientPackage, setSelectedClientPackage] = useState([])

  const campus = campuses.find(c => c.id === appointment.branch_campus_id)
  const court = courts.find(c => c.id === appointment.court_id)
  const coach = coaches.find(c => c.id === appointment.coach_id)

  // 加载预约相关数据
  const loadAppointmentData = async () => {
    const [clientsData, packagesData, assistantCoachesData] = await Promise.all([
      getCourseAppointmentClients(appointment.id),
      getCourseAppointmentPackages(appointment.id),
      getCourseAppointmentAssistantCoaches(appointment.id)
    ])

    setClients(clientsData)
    setPackages(packagesData)
    setAssistantCoaches(assistantCoachesData)
  }

  // 加载可用的学员和课程包 - 使用与约课页面相同的逻辑
  const loadAvailableClientsAndPackages = async () => {
    try {
      // 1. 获取该校区的所有学员
      const allClients = await getAllUsers({
        role: 'client',
        branch_campus_id: appointment.branch_campus_id,
        status: 'active'
      })
      console.log('获取的学员:', allClients)

      // 2. 获取该校区的所有课程包
      const coursePackages = await getCoursePackages({
        branch_campus_id: appointment.branch_campus_id,
        status: 'active'
      })
      console.log('获取的课程包:', coursePackages)

      // 3. 构建学员-课程包的级联数据（与约课页面逻辑完全一致）
      const cascadingData = allClients.map(client => {
        console.log(`正在处理学员: ${client.name} (ID: ${client.id})`)

        // 找到该学员的所有课程包
        const clientPackages = coursePackages.filter(pkg => {
          const match = pkg.client_id === client.id && pkg.left_count > 0
          console.log(`课程包 ${pkg.id}: client_id=${pkg.client_id}, left_count=${pkg.left_count}, 匹配=${match}`)
          return match
        })

        console.log(`学员 ${client.name} 的课程包:`, clientPackages)

        // 如果该学员有课程包，则构建子级选项
        return {
          label: client.name, // 学员姓名作为一级标签
          value: client.id,   // 学员ID作为一级值
          children: clientPackages.map(pkg => ({
            label: `${pkg.course_type} (剩余${pkg.left_count}课时)`, // 课程包名称和剩余课时作为二级标签
            value: pkg.id,    // 课程包ID作为二级值
          }))
        }
      }).filter(item => {
        const hasChildren = item.children.length > 0
        console.log(`学员 ${item.label} 有 ${item.children.length} 个课程包，保留=${hasChildren}`)
        return hasChildren
      })

      console.log('最终构建的级联数据:', cascadingData)
      setClientAndCoursePackages(cascadingData)
    } catch (error) {
      console.error('加载学员和课程包失败:', error)
    }
  }

  useEffect(() => {
    loadAppointmentData()
    loadAvailableClientsAndPackages()
  }, [appointment.id])

  // 添加助教
  const handleAddAssistant = async () => {
    if (!selectedCoachId) return

    const formData = new FormData()
    formData.append('appointment_id', appointment.id)
    formData.append('coach_id', selectedCoachId)
    formData.append('teaching_commission_rate', coachRate)

    const result = await addAssistantCoach(formData)
    if (result.success) {
      setSelectedCoachId("")
      setCoachRate(3)
      loadAppointmentData()
      onSuccess?.()
    }
  }

  // 删除助教
  const handleRemoveAssistant = async (coachId) => {
    const formData = new FormData()
    formData.append('appointment_id', appointment.id)
    formData.append('coach_id', coachId)

    const result = await removeAssistantCoach(formData)
    if (result.success) {
      loadAppointmentData()
      onSuccess?.()
    }
  }

  // 添加学员和课程包
  const handleAddClientPackage = async () => {
    if (selectedClientPackage.length === 0) return

    for (const item of selectedClientPackage) {
      const formData = new FormData()
      formData.append('appointment_id', appointment.id)
      formData.append('client_id', item.parent)  // 学员ID
      formData.append('package_id', item.child)  // 课程包ID

      await addClientWithPackage(formData)
    }

    setSelectedClientPackage([])
    loadAppointmentData()
    onSuccess?.()
  }

  // 删除学员和课程包
  const handleRemoveClientPackage = async (clientId, packageId) => {
    const formData = new FormData()
    formData.append('appointment_id', appointment.id)
    formData.append('client_id', clientId)
    formData.append('package_id', packageId)

    const result = await removeClientWithPackage(formData)
    if (result.success) {
      loadAppointmentData()
      onSuccess?.()
    }
  }

  // 过滤可用教练（排除主教练和已选助教）
  const availableCoaches = coaches.filter(c =>
    c.id !== appointment.coach_id &&
    !assistantCoaches.some(ac => ac.coach_id === c.id)
  )

  return (
    <div className="flex flex-col gap-4 max-h-[70vh] overflow-y-auto">
      {/* 基本信息 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">基本信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-2 text-sm">
            <div>校区: {campus?.name}</div>
            <div>场地: {court?.name}</div>
            <div>主教练: {coach?.name}</div>
            <div>时间: {format(appointment.start_time, "MM-dd HH:mm")} - {format(appointment.end_time, "HH:mm")}</div>
          </div>
        </CardContent>
      </Card>

      {/* 助教管理 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">助教管理</CardTitle>
        </CardHeader>
        <CardContent>
          {/* 当前助教列表 */}
          <div className="space-y-2 mb-4">
            {assistantCoaches.map(assistant => (
              <div key={assistant.coach_id} className="flex items-center justify-between p-2 border rounded">
                <div className="flex items-center gap-2">
                  <span>{coaches.find(c => c.id === assistant.coach_id)?.name}</span>
                  <Badge variant="outline">{assistant.teaching_commission_rate}%</Badge>
                </div>
                <Button
                  size="sm"
                  variant="destructive"
                  onClick={() => handleRemoveAssistant(assistant.coach_id)}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>

          {/* 添加新助教 */}
          <div className="flex gap-2 items-end">
            <div className="flex-1">
              <Label>选择助教</Label>
              <CommonSelector
                items={availableCoaches.map(coach => ({
                  value: coach.id,
                  label: coach.name
                }))}
                value={selectedCoachId}
                onValueChange={setSelectedCoachId}
                placeholder="选择助教"
              />
            </div>
            <div className="w-24">
              <Label>提成%</Label>
              <Input
                type="number"
                value={coachRate}
                onChange={(e) => setCoachRate(Number(e.target.value))}
                min="0"
                max="100"
              />
            </div>
            <Button onClick={handleAddAssistant} disabled={!selectedCoachId}>
              <Plus className="h-4 w-4" />
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 学员和课程包管理 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">学员管理</CardTitle>
        </CardHeader>
        <CardContent>
          {/* 当前学员列表 */}
          <div className="space-y-2 mb-4">
            {clients.map((client) => {
              const clientPackage = packages.find(p => p.course_package.client_id === client.client_id)
              return (
                <div key={client.id} className="flex items-center justify-between p-2 border rounded">
                  <div className="flex items-center gap-2">
                    <span>{client?.client?.name}</span>
                    <Badge variant="outline">{clientPackage?.course_package?.course_type}</Badge>
                    <span className="text-sm text-gray-500">
                      剩余{clientPackage?.course_package?.left_count || 0}节
                    </span>
                  </div>
                  <Button
                    size="sm"
                    variant="destructive"
                    onClick={() => handleRemoveClientPackage(
                      client.client_id,
                      clientPackage?.course_package_id
                    )}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              )
            })}
          </div>

          {/* 添加新学员 */}
          <div className="space-y-2">
            <Label>添加学员和课程包</Label>
            <ComboboxMultiGroupSelector
              options={clientAndCoursePackages}
              value={selectedClientPackage}
              onChange={setSelectedClientPackage}
              placeholder="选择学员和课程包"
              emptyText="没有可用的学员或课程包"
              searchPlaceholder="搜索学员或课程包..."
            />
            <Button
              onClick={handleAddClientPackage}
              disabled={selectedClientPackage.length === 0}
              className="w-full"
            >
              添加选中的学员
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
